package com.nondo.dean.product.mapper;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import com.nondo.dean.product.model.param.ProductQueryParam;

public class ProductExtendsSqlProvider {

    public String selectChildListByCode(ProductQueryParam productParam) {
        SQL sql = new SQL();
        sql.SELECT("product.id");
        sql.SELECT("product.code");
        sql.SELECT("product.name");
        sql.SELECT("product.stock");
        sql.SELECT("product.order_flag");
        sql.SELECT("product.main_image");
        sql.SELECT("product.sale_price");
        sql.SELECT("product.descrption");
        sql.FROM("product_bom bom,product product");
        applyWhere(sql, productParam);
        return sql.toString();
    }

    /**
     * 第二种写法不包含主产品
     * SELECT product.* FROM product_bom bom, product product WHERE bom.product_code=product.`code` AND
        bom.parent_product_code='E8105E-01' UNION
        SELECT product.* FROM product_bom bom, product product WHERE bom.product_code=product.`code` AND parent_product_code=(SELECT parent_product_code FROM product_bom WHERE product_code = 'E8105E-01');
     * @param sql
     * @param productParam
     */
    
    protected void applyWhere(SQL sql, ProductQueryParam productParam) {
        if (productParam == null) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("bom.product_code=product.`code`");
        if(StringUtils.isNotEmpty(productParam.getName())){
            sb.append(" AND product.`name` like '").append(productParam.getName()).append("%'");
        }
        if(StringUtils.isNotEmpty(productParam.getCode())){
            sb.append(" AND LOCATE(SUBSTR((SELECT num FROM product_bom WHERE product_code = '").append(productParam.getCode()).append("'),1,4),num)");
        }
        if (sb.length() > 0) {
            sql.WHERE(sb.toString());
        }
    }
}